import 'dart:async';
import 'dart:io';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart' as video_player;
import '../../function/model/post_model.dart';

/// 视频播放器控制器
class VideoPlayerController extends GetxController {
  video_player.VideoPlayerController? _videoPlayerController;
  final RxBool _isInitialized = false.obs;
  final RxBool _isPlaying = false.obs;
  final RxBool _isLoading = true.obs;
  final RxString _errorMessage = ''.obs;
  final RxDouble _playbackSpeed = 1.0.obs;
  final RxBool _showControls = true.obs;

  // 当前播放的视频信息
  PostModel? _currentPost;
  String? _videoPath;
  bool _isAssetVideo = false;

  // 时间更新定时器
  Timer? _timeUpdateTimer;

  /// 获取视频播放器控制器
  video_player.VideoPlayerController? get videoPlayerController =>
      _videoPlayerController;

  /// 是否已初始化
  bool get isInitialized => _isInitialized.value;

  /// 是否正在播放
  bool get isPlaying => _isPlaying.value;

  /// 是否正在加载
  bool get isLoading => _isLoading.value;

  /// 错误信息
  String get errorMessage => _errorMessage.value;

  /// 播放速度
  double get playbackSpeed => _playbackSpeed.value;

  /// 是否显示控制栏
  bool get showControls => _showControls.value;

  /// 当前帖子
  PostModel? get currentPost => _currentPost;

  @override
  void onInit() {
    super.onInit();
    _initializeVideo();
  }

  @override
  void onClose() {
    _timeUpdateTimer?.cancel();
    _videoPlayerController?.dispose();
    super.onClose();
  }

  /// 初始化视频
  void _initializeVideo() {
    try {
      // 获取传递的参数
      final arguments = Get.arguments;
      if (arguments is PostModel) {
        _currentPost = arguments;
        _videoPath = arguments.resourcePath;
        _isAssetVideo = arguments.resourcePath.startsWith('assets/');
      } else if (arguments is Map<String, dynamic>) {
        _videoPath = arguments['videoPath'] as String?;
        _isAssetVideo = arguments['isAssetVideo'] as bool? ?? false;
        _currentPost = arguments['post'] as PostModel?;
      }

      if (_videoPath == null || _videoPath!.isEmpty) {
        _errorMessage.value = 'Video path not provided';
        _isLoading.value = false;
        return;
      }

      _loadVideo();
    } catch (e) {
      _errorMessage.value = 'Failed to initialize video: ${e.toString()}';
      _isLoading.value = false;
    }
  }

  /// 加载视频
  Future<void> _loadVideo() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';

      if (_isAssetVideo) {
        // 加载assets中的视频
        _videoPlayerController = video_player.VideoPlayerController.asset(
          _videoPath!,
        );
      } else {
        // 加载本地文件视频
        final file = File(_videoPath!);
        if (!await file.exists()) {
          throw Exception('Video file does not exist');
        }
        _videoPlayerController = video_player.VideoPlayerController.file(file);
      }

      await _videoPlayerController!.initialize();

      // 设置监听器
      _videoPlayerController!.addListener(_videoListener);

      _isInitialized.value = true;
      _isLoading.value = false;

      // 启动时间更新定时器
      _startTimeUpdateTimer();

      // 自动播放
      play();
    } catch (e) {
      _errorMessage.value = 'Failed to load video: ${e.toString()}';
      _isLoading.value = false;
    }
  }

  /// 视频监听器
  void _videoListener() {
    if (_videoPlayerController != null) {
      _isPlaying.value = _videoPlayerController!.value.isPlaying;
    }
  }

  /// 启动时间更新定时器
  void _startTimeUpdateTimer() {
    _timeUpdateTimer?.cancel();
    _timeUpdateTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_videoPlayerController != null) {
        update(); // 触发UI更新
      }
    });
  }

  /// 停止时间更新定时器
  void _stopTimeUpdateTimer() {
    _timeUpdateTimer?.cancel();
    _timeUpdateTimer = null;
  }

  /// 播放/暂停
  void togglePlayPause() {
    if (_videoPlayerController == null) return;

    if (_isPlaying.value) {
      pause();
    } else {
      play();
    }
  }

  /// 播放
  void play() {
    _videoPlayerController?.play();
  }

  /// 暂停
  void pause() {
    _videoPlayerController?.pause();
  }

  /// 停止
  void stop() {
    _videoPlayerController?.pause();
    _videoPlayerController?.seekTo(Duration.zero);
  }

  /// 设置播放位置
  void seekTo(Duration position) {
    _videoPlayerController?.seekTo(position);
  }

  /// 设置播放速度
  void setPlaybackSpeed(double speed) {
    _playbackSpeed.value = speed;
    _videoPlayerController?.setPlaybackSpeed(speed);
  }

  /// 切换控制栏显示
  void toggleControls() {
    _showControls.value = !_showControls.value;
  }

  /// 隐藏控制栏
  void hideControls() {
    _showControls.value = false;
  }

  /// 显示控制栏
  void showControlsBar() {
    _showControls.value = true;
  }

  /// 获取视频时长
  Duration? get duration {
    return _videoPlayerController?.value.duration;
  }

  /// 获取当前播放位置
  Duration? get position {
    return _videoPlayerController?.value.position;
  }

  /// 重新加载视频
  Future<void> reloadVideo() async {
    _stopTimeUpdateTimer();
    if (_videoPlayerController != null) {
      _videoPlayerController!.dispose();
    }
    _isInitialized.value = false;
    _isPlaying.value = false;
    _isLoading.value = true;
    _errorMessage.value = '';
    await _loadVideo();
  }

  /// 返回上一页
  void goBack() {
    stop();
    Get.back();
  }
}
